package com.xxxx.springboot.shiro.config;

import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

	private String SHIRO_ERROR = "SHIRO_ERROR";

	private String SERVER_ERROR = "500";

	@ExceptionHandler
	public ResultVO apiExceptionHandler(Exception ex) {
		/**
		 * DisabledAccountException（禁用的帐号）、LockedAccountException（锁定的帐号）、UnknownAccountException（错误的帐号）、
		 * ExcessiveAttemptsException（登录失败次数过多）、IncorrectCredentialsException
		 * （错误的凭证）、ExpiredCredentialsException（过期的凭证）
		 * 
		 * AuthorizationException
		 */
		if (ex instanceof ExcessiveAttemptsException) {
			return ResultVO.error(SHIRO_ERROR, "登录失败次数过多");
		} else if (ex instanceof AccountException || ex instanceof IncorrectCredentialsException) {
			return ResultVO.error(SHIRO_ERROR, "用户名或者密码错误");
		} else if (ex instanceof ExpiredCredentialsException) {
			return ResultVO.error(SHIRO_ERROR, "登陆失效，请重新登陆");
		} else if (ex instanceof UnauthorizedException) {
			return ResultVO.error(SHIRO_ERROR, "登陆用户无权限");
		} else if (ex instanceof UnauthenticatedException) {// TODO 无法捕获，等下研究
			return ResultVO.error(SHIRO_ERROR, "用户未登录");
		} else {
			return ResultVO.error(SERVER_ERROR, ex.getMessage());
		}
	}

}
